/**
 * Copyright 2016- the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inmorn.orm.mybatis.transaction;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jeff.Li
 * @date 2016年11月10日
 * 注:扩展原mybatis-spring.jar
 */
public class MornManagedTransaction implements Transaction {

	protected final Logger LOG = LoggerFactory.getLogger(getClass());

	private final DataSource dataSource;

	private Connection connection;

	private boolean isConnectionTransactional;

	private boolean autoCommit;

	public MornManagedTransaction(DataSource dataSource) {
		if (dataSource == null) {
			throw new IllegalArgumentException("No DataSource specified");
		}
		this.dataSource = dataSource;
	}

	public Connection getConnection() throws SQLException {
		if (this.connection == null) {
			openConnection();
		}
		return this.connection;
	}

	private void openConnection() throws SQLException {
		this.connection = this.dataSource.getConnection();
		this.autoCommit = this.connection.getAutoCommit();
		this.isConnectionTransactional = false;
//		this.isConnectionTransactional = DataSourceUtils
//				.isConnectionTransactional(this.connection, this.dataSource);

		if (LOG.isDebugEnabled()) {
			LOG.debug("JDBC Connection [" + this.connection + "] will"
					+ (this.isConnectionTransactional ? " " : " not ")
					+ "be managed by Spring");
		}
	}

	public void commit() throws SQLException {
		if (this.connection != null && !this.isConnectionTransactional
				&& !this.autoCommit) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Committing JDBC Connection [" + this.connection
						+ "]");
			}
			this.connection.commit();
		}

	}

	public void rollback() throws SQLException {
		if (this.connection != null && !this.isConnectionTransactional
				&& !this.autoCommit) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("Rolling back JDBC Connection [" + this.connection
						+ "]");
			}
			this.connection.rollback();
		}

	}

	public void close() throws SQLException {
		if(connection != null){
			connection.close();
		}
	}

}
